<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        class Mypromise{
            constructor(executor){
                this._state = "pending";
                this._result = undefined;
                this._fulfilledList = [];
                this._rejectedList = [];

                // 如果executor为空，就执行executor()
                // 形参传的两个内部方法
                // 前面这个this乱指，然后bind里面的this指向实例
                executor && executor(this.resolve.bind(this),this.reject.bind(this));
            }

            // 实参
            resolve(result){
                if(this._state === "pending"){
                    this._state = "fulfilled";
                    this._result = result;
                    // pop() 方法用于删除数组的最后一个元素并返回删除的元素。
                    const fulfilled = this._fulfilledList.pop();
                    fulfilled && fulfilled(this._result);//这个this是then里面的result-> resolve(result)再给他的

                }

            }
            // 实参
            reject(error){
                if(this._state === "pending"){
                    this._state = "rejected";
                    this._result = error;
                    const rejected = this._rejectedList.pop();
                    rejected && rejected(this._result);
            }
        }

        // 自定义两个函数接收值
            then(onfulfilled,onrejected){
                if(this._state === "fulfilled"){
                    onfulfilled(this._result);
                }else if(this._state === "rejected"){
                    onrejected(this._result);
                }else if(this._state === "pending"){
                    this._fulfilledList.push(onfulfilled);
                    this._rejectedList.push(onrejected);
                }

            }
        }
        // 实参
        let p = new Mypromise((resolve,reject) =>{
            console.log(this);
            console.log("立即执行");
            // resolve("成功");
            // reject("失败");

            setTimeout(() =>{
                resolve("成功");
            },2000)

        })
        console.log(p);

        p.then((result) =>{
            console.log(result);
        },error =>{
            console.log(error);
        })



        // resolve(){
            
        // }
        // this.resolve;

        // function fn(){

        // }
        // this.fn
    
    </script>
</body>
</html>